import { ref, computed } from 'vue'

// 菜单项接口
export interface MenuItem {
  title: string
  path: string
  icon?: any
  children?: MenuItem[]
  badge?: number | string
  tag?: string
  tagType?: 'success' | 'warning' | 'danger' | 'info'
  external?: boolean
  disabled?: boolean
  hidden?: boolean
  permission?: string
  order?: number
  meta?: {
    requiresAuth?: boolean
    roles?: string[]
    permissions?: string[]
    keepAlive?: boolean
    title?: string
    icon?: string
  }
}

// 菜单管理类
export class MenuManager {
  private static instance: MenuManager
  private menuCache = new Map<string, MenuItem[]>()
  private userPermissions = ref<string[]>([])
  private userRoles = ref<string[]>([])

  static getInstance(): MenuManager {
    if (!MenuManager.instance) {
      MenuManager.instance = new MenuManager()
    }
    return MenuManager.instance
  }

  // 设置用户权限
  setUserPermissions(permissions: string[]) {
    this.userPermissions.value = permissions
  }

  // 设置用户角色
  setUserRoles(roles: string[]) {
    this.userRoles.value = roles
  }

  // 检查权限
  hasPermission(permission?: string): boolean {
    if (!permission) return true
    return this.userPermissions.value.includes(permission)
  }

  // 检查角色
  hasRole(roles?: string[]): boolean {
    if (!roles || roles.length === 0) return true
    return roles.some(role => this.userRoles.value.includes(role))
  }

  // 过滤菜单权限
  filterMenuByPermission(menuItems: MenuItem[]): MenuItem[] {
    return this.filterMenuByPermissionRecursive(menuItems, 0)
  }

  // 递归过滤菜单权限，添加深度限制
  private filterMenuByPermissionRecursive(menuItems: MenuItem[], depth: number): MenuItem[] {
    // 限制菜单深度，防止过深的嵌套
    if (depth > 3) {
      console.warn('菜单深度超过限制，已截断:', depth)
      return []
    }

    return menuItems.filter(item => {
      // 检查权限
      if (item.permission && !this.hasPermission(item.permission)) {
        return false
      }

      // 检查角色
      if (item.meta?.roles && !this.hasRole(item.meta.roles)) {
        return false
      }

      // 检查子菜单
      if (item.children && item.children.length > 0) {
        const filteredChildren = this.filterMenuByPermissionRecursive(item.children, depth + 1)
        if (filteredChildren.length > 0) {
          item.children = filteredChildren
          return true
        }
        return false
      }

      return true
    })
  }

  // 搜索菜单
  searchMenu(menuItems: MenuItem[], keyword: string): MenuItem[] {
    if (!keyword) return menuItems
    return this.searchMenuRecursive(menuItems, keyword.toLowerCase(), 0)
  }

  // 递归搜索菜单，添加深度限制
  private searchMenuRecursive(menuItems: MenuItem[], keyword: string, depth: number): MenuItem[] {
    // 限制搜索深度
    if (depth > 3) {
      return []
    }

    return menuItems.filter(item => {
      const titleMatch = item.title.toLowerCase().includes(keyword)

      if (item.children && item.children.length > 0) {
        const filteredChildren = this.searchMenuRecursive(item.children, keyword, depth + 1)
        if (filteredChildren.length > 0) {
          item.children = filteredChildren
          return true
        }
      }

      return titleMatch
    })
  }

  // 获取菜单路径
  getMenuPath(menuItems: MenuItem[], targetPath: string): MenuItem[] {
    const path: MenuItem[] = []

    function findPath(items: MenuItem[], target: string, currentPath: MenuItem[], depth: number): boolean {
      // 限制搜索深度
      if (depth > 3) {
        return false
      }

      for (const item of items) {
        const newPath = [...currentPath, item]

        if (item.path === target) {
          path.push(...newPath)
          return true
        }

        if (item.children && item.children.length > 0) {
          if (findPath(item.children, target, newPath, depth + 1)) {
            return true
          }
        }
      }
      return false
    }

    findPath(menuItems, targetPath, [], 0)
    return path
  }

  // 获取面包屑导航
  getBreadcrumb(menuItems: MenuItem[], currentPath: string): MenuItem[] {
    return this.getMenuPath(menuItems, currentPath)
  }

  // 展开所有菜单
  expandAllMenus(menuItems: MenuItem[]): string[] {
    const expandedKeys: string[] = []

    function collectKeys(items: MenuItem[], depth: number = 0) {
      // 限制展开深度
      if (depth > 3) {
        return
      }

      items.forEach(item => {
        if (item.children && item.children.length > 0) {
          expandedKeys.push(item.path)
          collectKeys(item.children, depth + 1)
        }
      })
    }

    collectKeys(menuItems)
    return expandedKeys
  }

  // 获取菜单统计信息
  getMenuStats(menuItems: MenuItem[]) {
    let totalItems = 0
    let totalBadges = 0
    let maxDepth = 0
    let totalChildren = 0

    function analyze(items: MenuItem[], depth: number = 1) {
      // 限制分析深度
      if (depth > 3) {
        return
      }

      items.forEach(item => {
        totalItems++
        if (item.badge) {
          totalBadges += typeof item.badge === 'number' ? item.badge : 1
        }
        maxDepth = Math.max(maxDepth, depth)

        if (item.children && item.children.length > 0) {
          totalChildren += item.children.length
          analyze(item.children, depth + 1)
        }
      })
    }

    analyze(menuItems)

    return {
      totalItems,
      totalBadges,
      maxDepth: Math.min(maxDepth, 3), // 限制最大深度显示
      totalChildren,
      averageDepth: totalItems > 0 ? Math.min(maxDepth, 3) / totalItems : 0,
      hasDeepNesting: maxDepth > 2
    }
  }

  // 验证菜单结构
  validateMenuStructure(menuItems: MenuItem[]): { isValid: boolean; errors: string[] } {
    const errors: string[] = []

    function validate(items: MenuItem[], depth: number = 1, path: string = '') {
      if (depth > 3) {
        errors.push(`菜单深度超过限制: ${path} (深度: ${depth})`)
        return
      }

      items.forEach((item, index) => {
        const currentPath = path ? `${path} > ${item.title}` : item.title

        // 检查必要字段
        if (!item.title || !item.path) {
          errors.push(`菜单项缺少必要字段: ${currentPath}`)
        }

        // 检查路径格式
        if (item.path && !item.path.startsWith('/') && !item.external) {
          errors.push(`菜单路径格式错误: ${currentPath} (${item.path})`)
        }

        // 检查子菜单数量
        if (item.children && item.children.length > 10) {
          errors.push(`菜单项子项过多: ${currentPath} (${item.children.length}项，建议分组)`)
        }

        // 检查子菜单
        if (item.children && item.children.length > 0) {
          validate(item.children, depth + 1, currentPath)
        }
      })
    }

    validate(menuItems)

    return {
      isValid: errors.length === 0,
      errors
    }
  }

  // 优化菜单结构
  optimizeMenuStructure(menuItems: MenuItem[]): MenuItem[] {
    return menuItems.map(item => {
      const optimizedItem = { ...item }

      // 如果子菜单过多，建议分组或提升为顶级菜单
      if (item.children && item.children.length > 8) {
        console.warn(`菜单项 "${item.title}" 子项过多 (${item.children.length})，建议优化`)

        // 自动分组：如果子项超过8个，尝试按功能分组
        if (item.children.length > 12) {
          optimizedItem.children = this.groupMenuItems(item.children)
        }
      }

      // 递归优化子菜单
      if (item.children && item.children.length > 0) {
        optimizedItem.children = this.optimizeMenuStructure(item.children)
      }

      return optimizedItem
    })
  }

  // 新增：菜单项分组方法
  private groupMenuItems(menuItems: MenuItem[]): MenuItem[] {
    // 如果子项过多，尝试按功能分组
    if (menuItems.length <= 8) {
      return menuItems
    }

    // 简单的分组逻辑：按标题长度或其他规则分组
    const groups: { [key: string]: MenuItem[] } = {}

    menuItems.forEach(item => {
      // 根据标题的第一个字符进行简单分组
      const firstChar = item.title.charAt(0)
      if (!groups[firstChar]) {
        groups[firstChar] = []
      }
      groups[firstChar].push(item)
    })

    // 将分组转换为菜单结构
    const groupedMenu: MenuItem[] = []
    Object.entries(groups).forEach(([key, items]) => {
      if (items.length === 1) {
        // 如果分组只有一个项目，直接添加
        groupedMenu.push(items[0])
      } else {
        // 如果分组有多个项目，创建子菜单
        groupedMenu.push({
          title: `${key}类管理`,
          path: `${items[0].path}-group`,
          children: items
        })
      }
    })

    return groupedMenu
  }

  // 缓存菜单
  cacheMenu(key: string, menuItems: MenuItem[]) {
    this.menuCache.set(key, JSON.parse(JSON.stringify(menuItems)))
  }

  // 获取缓存的菜单
  getCachedMenu(key: string): MenuItem[] | null {
    const cached = this.menuCache.get(key)
    return cached ? JSON.parse(JSON.stringify(cached)) : null
  }

  // 清除缓存
  clearCache() {
    this.menuCache.clear()
  }

  // 菜单排序
  sortMenu(menuItems: MenuItem[]): MenuItem[] {
    const sorted = [...menuItems].sort((a, b) => (a.order || 0) - (b.order || 0))

    sorted.forEach(item => {
      if (item.children && item.children.length > 0) {
        item.children = this.sortMenu(item.children)
      }
    })

    return sorted
  }

  // 扁平化菜单
  flattenMenu(menuItems: MenuItem[]): MenuItem[] {
    const flat: MenuItem[] = []

    function flatten(items: MenuItem[]) {
      items.forEach(item => {
        flat.push({ ...item, children: undefined })
        if (item.children && item.children.length > 0) {
          flatten(item.children)
        }
      })
    }

    flatten(menuItems)
    return flat
  }

  // 根据路径查找菜单项
  findMenuItemByPath(menuItems: MenuItem[], path: string): MenuItem | null {
    for (const item of menuItems) {
      if (item.path === path) {
        return item
      }
      if (item.children && item.children.length > 0) {
        const found = this.findMenuItemByPath(item.children, path)
        if (found) return found
      }
    }
    return null
  }

  // 获取菜单树的最大深度
  getMaxDepth(menuItems: MenuItem[]): number {
    let maxDepth = 0

    function getDepth(items: MenuItem[], depth: number = 1) {
      maxDepth = Math.max(maxDepth, depth)
      items.forEach(item => {
        if (item.children && item.children.length > 0) {
          getDepth(item.children, depth + 1)
        }
      })
    }

    getDepth(menuItems)
    return maxDepth
  }
}

// 导出单例实例
export const menuManager = MenuManager.getInstance()

// 组合式函数
export function useMenuManager() {
  const manager = menuManager

  return {
    manager,
    userPermissions: computed(() => manager['userPermissions'].value),
    userRoles: computed(() => manager['userRoles'].value),
    setUserPermissions: (permissions: string[]) => manager.setUserPermissions(permissions),
    setUserRoles: (roles: string[]) => manager.setUserRoles(roles),
    filterMenuByPermission: (menuItems: MenuItem[]) => manager.filterMenuByPermission(menuItems),
    searchMenu: (menuItems: MenuItem[], keyword: string) => manager.searchMenu(menuItems, keyword),
    getBreadcrumb: (menuItems: MenuItem[], currentPath: string) => manager.getBreadcrumb(menuItems, currentPath),
    getMenuStats: (menuItems: MenuItem[]) => manager.getMenuStats(menuItems),
    validateMenuStructure: (menuItems: MenuItem[]) => manager.validateMenuStructure(menuItems),
    optimizeMenuStructure: (menuItems: MenuItem[]) => manager.optimizeMenuStructure(menuItems)
  }
}
